<script setup lang="ts">
import { ref, defineProps, defineEmits, withDefaults, watch, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { addDeviceGroupApi, getDeviceGroupOptionsApi } from "@/api/products/deviceGroup";
import { useLogic } from "@/views/system/user/logic/logic";
import { buildTree } from '@/utils/helper';
import { getGroupPurposeOptions } from '@/utils/appCommon/appCommonOptions/deviceGroup'
import { useI18n } from "vue-i18n";

const {deptTreeList,getDeptTree}  = useLogic()
const { t } = useI18n();

// 设备分组选项列表
const deviceGroupOptions = ref<any[]>([]);
const treeDeviceGroupOptions = ref<any[]>([]);
const purposeOptions = ref<Array<{ val: string; label: string }>>([])

// 获取设备分组选项
const getDeviceGroupOptions = async () => {
  try {
    const response = await getDeviceGroupOptionsApi();
    if (response.code === 0) {
      deviceGroupOptions.value = response.data?.options || [];
      // 构建树形结构选项（排除自己）
      treeDeviceGroupOptions.value = buildTree(deviceGroupOptions.value, 'id', 'parentId', 'children');
    }
  } catch (error) {
    console.error('Failed to get device group options:', error);
  }
};

onMounted(async () => {
  purposeOptions.value = await getGroupPurposeOptions();
  await Promise.all([getDeptTree(), getDeviceGroupOptions()]);
});

// 定义props
const props = withDefaults(defineProps<{
  visible: boolean;
}>(), {
  visible: false
});

// 本地状态管理弹窗显示
const dialogVisible = ref(props.visible);

// 同步props到本地状态
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal;
}, { immediate: true });

// 通知父组件状态变化
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal);
});

// 定义emits
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void;
  (e: 'close'): void;
  (e: 'success'): void;
}>();

// 表单数据
const formData = ref<{
  groupName: string;
  groupKey: string;
  purpose: string;
  deptId: number;
  remark: string;
  parentId: number; // 新增父分组ID字段
}>({
  groupName: '',
  groupKey: '',
  purpose: '',
  deptId: 0,
  remark: '',
  parentId: 0 // 默认无父分组
});

// 提交表单
const submitForm = async () => {
  try {
    const submitData = {
      groupKey: formData.value.groupKey,
      name: formData.value.groupName,
      purpose: formData.value.purpose,
      deptId: formData.value.deptId,
      remark: formData.value.remark,
      parentId: formData.value.parentId // 包含父分组ID
    };

    const response = await addDeviceGroupApi(submitData);
    if (response.code === 0) {
      ElMessage.success(t("products.deviceGroupPage.addSuccess"));
      emit('update:visible', false);
      emit('success');
      resetForm();
    } else {
      ElMessage.error(response.msg || t("products.deviceGroupPage.addFailed"));
    }
  } catch (error) {
    ElMessage.error(t("products.deviceGroupPage.addFailed"));
    console.error('Failed to add device group:', error);
  }
};

// 重置表单
const resetForm = () => {
  formData.value = {
    groupName: '',
    groupKey: '',
    purpose: '',
    deptId: 0,
    remark: '',
    parentId: 0
  };
};

// 关闭弹窗
const closeDialog = () => {
  emit('update:visible', false);
  emit('close');
};



</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="t('products.deviceGroupPage.addGroup')"
    :draggable="true"
    @close="closeDialog"
    width="600px"
  >
    <el-form
      :model="formData"
      label-width="120px"
      style="max-width: 500px; margin: 0 auto;"
    >
      <el-form-item :label="t('products.deviceGroupPage.groupName')" prop="groupName" required>
        <el-input v-model="formData.groupName" :placeholder="t('products.deviceGroupPage.searchPlaceholder')" />
      </el-form-item>
      <el-form-item :label="t('products.deviceGroupPage.groupKey')" prop="groupKey" required>
        <el-input v-model="formData.groupKey" :placeholder="t('products.deviceGroupPage.searchPlaceholder')" />
        <div style="text-align: center; font-size: 12px; color: red">{{ t('products.deviceGroupPage.groupKeyHint') }}</div>
      </el-form-item>
      <el-form-item :label="t('products.deviceGroupPage.purpose')" prop="purpose">
        <el-select v-model="formData.purpose" :placeholder="t('products.deviceGroupPage.searchPlaceholder')">
          <el-option
            v-for="item in purposeOptions"
            :key="item.val"
            :label="item.label"
            :value="item.val"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('products.deviceGroupPage.dept')" prop="deptId">
        <el-cascader
          v-model="formData.deptId"
          class="w-full"
          :options="deptTreeList"
          :props="{
              value: 'id',
              label: 'name',
              emitPath: false,
              checkStrictly: true
            }"
          clearable
          filterable
          :placeholder="t('products.deviceGroupPage.searchPlaceholder')"
        >
          <template #default="{ node, data }">
            <span>{{ data.name }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </el-form-item>
      <el-form-item :label="t('products.deviceGroupPage.remark')" prop="remark">
        <el-input v-model="formData.remark" :placeholder="t('products.deviceGroupPage.searchPlaceholder')" type="textarea" />
      </el-form-item>

      <!-- 新增父分组选择 -->
      <el-form-item :label="t('products.deviceGroupPage.parentGroup')" prop="parentId">
        <el-cascader
          v-model="formData.parentId"
          class="w-full"
          :options="treeDeviceGroupOptions"
          :props="{
              value: 'id',
              label: 'name',
              emitPath: false,
              checkStrictly: true
            }"
          clearable
          filterable
          :placeholder="t('products.deviceGroupPage.rootGroupTip')"
        >
          <template #default="{ node, data }">
            <span>{{ data.name }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm">{{ t("buttons.reset") }}</el-button>
        <el-button type="primary" @click="submitForm">{{ t("buttons.submit") }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>


